package lbframework.bean.tree;

import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class LBTree extends JTree {

    public LBTree() {
        initComponents();

        setModel(null);

        setRootVisible(false);
        getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    }

    public DefaultMutableTreeNode getSelectedNode() {
        return (DefaultMutableTreeNode) this.getLastSelectedPathComponent();
    }

    public void removeNode(DefaultMutableTreeNode i_node) {
        ((DefaultTreeModel) this.getModel()).removeNodeFromParent(i_node);
    }

    public void expandAll(boolean expand) {
        TreeNode root = (TreeNode) this.getModel().getRoot();
        // Traverse tree from root
        expandAll(new TreePath(root), expand);
    }

    private void expandAll(TreePath parent, boolean expand) {
        // Traverse children
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(path, expand);
            }
        }
        // Expansion or collapse must be done bottom-up
        if (expand) {
            this.expandPath(parent);
        } else {
            this.collapsePath(parent);
        }
    }

    public void requestFocusLater() {
        Runnable doFocus = new Runnable() {

            public void run() {
                requestFocus();
            }
        };

        SwingUtilities.invokeLater(doFocus);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setModel(null);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });
    }// </editor-fold>//GEN-END:initComponents

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
        if (this.getRowCount() == 0) {
            this.transferFocus();
        } else {
            if (this.getLastSelectedPathComponent() == null) {
                this.setSelectionInterval(0, 0);
            }
        }
    }//GEN-LAST:event_formFocusGained
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
